/*
 * @LastEditTime: 2023-04-15 18:55:24
 */
import { User } from "../Models/User.schema";
import { updataUserDTO, createUserDTO } from "../DTO/User.dto";
import { isExistsforUsername } from "../hook";
import { createToken, encrypt, decrypt } from "../../utils/token.utli";
import { createCollectionDTO } from "../DTO/Collection.dto";

import { Context } from "koa";

export class AuthController {
  constructor(private readonly UserModel: typeof User) { }

  /**
   * 注册
   * @param ctx 上下文对象
   * @param dto 数据传输对象
   * @returns 返回token
   */
  async register(ctx: Context, dto: createUserDTO) {
    try {
      // 用户是否存在
      if (await isExistsforUsername(dto.username, User)) {
        // 加密
        const encryptStr = encrypt(dto.password);
        // 写入数据库
        const res = await this.UserModel.create({
          ...dto,
          iv: encryptStr.iv,
          password: encryptStr.content,
        });
        return {
          code: 200,
          message: "注册成功",
          data: {
            username: dto.username,
          },
        };
      } else {
        // 状态设置400
        ctx.status = 400;
        return {
          code: 400,
          message: "注册失败，用户已经存在",
        };
      }
    } catch (error) {
      return error;
    }
  }

  /**
   *
   * @param ctx 上下文对象
   * @param data ``` javascript
   *  username: string;
   *  password: string
   * ```
   * @returns
   */
  async login(ctx: Context, data: { username: string; password: string }) {
    try {
      // 检测是否存在该用户
      if (await isExistsforUsername(data.username, User)) {
        ctx.status = 400;
        return {
          code: 400,
          message: "用户名不存在",
        };
      } else {
        // 检测密码是否正确
        // 解密数据库密文 对比前端明文
        const useritem = await this.UserModel.find({ username: data.username });
        // 解密
        const password = decrypt({
          iv: useritem[0].iv as string,
          content: useritem[0].password as string,
        });
        // 比对密码
        if (password === data.password) {
          // 密码正确
          return {
            code: 200,
            message: "登录成功",
            data: {
              token: createToken(ctx, { username: data.username }),
            },
          };
        } else {
          // 密码错误
          ctx.status = 400;
          return {
            code: 400,
            message: "账号或密码不正确",
          };
        }
      }
    } catch (error) {
      return error;
    }
  }
}
